//////
//////		TODO: Menu and preferences stuff
//////			  
//////			  Saving of last used IP adress to external file
//////			  Logging to external file
//////			  ( http://wiki.answers.com/Q/How_do_you_call_an_external_file_in_java )				
//////			  
//////			  Text colours?
//////				|
//////				----> Andrea could you change the JTextArea to a JTextPane or something
//////						( http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html )
//////				
//////					Maybe someday:
//////					http://www.ddj.com/184404478


import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import javax.swing.border.*;
import sun.audio.*;
import java.util.Date;
import java.util.GregorianCalendar;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
   
public class ClientGui extends JFrame implements ActionListener, KeyListener
{
  
    //Sets all the attibutes of the chat server window and contents (buttons etc.)	  
	JLabel title = new JLabel("JNetProtect Remote Admin  "); 
  
	JTextField inMessage = new JTextField( 43 );
	JTextField ipBox = new JTextField( 13 );
  
	JButton sendBtn = new JButton("Send");
  	JButton connectBtn = new JButton("Connect");
  	JButton configBtn = new JButton ("Configure");
  
	JTextArea chatArea = new JTextArea("========================================== \n JNetProtect Remote Admin Console - version 1.8 \n ==========================================",15, 50);
	JScrollPane scrollPane = new JScrollPane(chatArea);
	
	JPanel southPanel = new JPanel();
	JPanel eastPanel = new JPanel();
	JPanel northPanel = new JPanel();

    Socket clisocket;
	PrintWriter out ;
	BufferedReader in ;
      
 
  public ClientGui()   
  {  
   
		title.setFont(new Font("Arial", Font.PLAIN, 23));
   
    	setTitle( "JNetProtect Remote Admin" );
   
  		 // Gives each object a frame
   		southPanel.setLayout(new FlowLayout());
   		southPanel.add(inMessage);
   		southPanel.add(sendBtn);
   	
   		northPanel.setLayout(new FlowLayout());
   		northPanel.add(title);
   		northPanel.add(ipBox);		
   		northPanel.add(connectBtn);
   		
		//adds listener to buttons
	    connectBtn.addActionListener(this);
	    sendBtn.addActionListener(this);
	    configBtn.addActionListener(this);    
	    inMessage.addKeyListener(this);
	    
	    //Attributes of the text area
	    chatArea.setFont(new Font("Arial", Font.PLAIN, 12));
		chatArea.setLineWrap(true);
		chatArea.setWrapStyleWord(true);
		chatArea.setEditable(false);
		chatArea.setSize(610, 2000);

		
	
	  	getContentPane().add(northPanel,BorderLayout.NORTH);
	  	getContentPane().add(scrollPane,BorderLayout.CENTER);    
	    getContentPane().add(southPanel,BorderLayout.SOUTH);
	    getContentPane().add(eastPanel,BorderLayout.EAST);
	    
	    sendBtn.setEnabled(false);
		connectBtn.setEnabled(true);
		
    
  }
 
   
  public void actionPerformed(ActionEvent evt)  
  {
         		
        String userIn ;
        String ipAdress;
        
    		try{
          		
          		
          		if(evt.getSource() == connectBtn)
          		{
					ipAdress = ipBox.getText();
								
		            System.out.println("Client Trying to Connect");
		            clisocket = new Socket(ipAdress, 4444);
		           
		            in = new BufferedReader(new InputStreamReader( clisocket.getInputStream()));
		            out =new PrintWriter(clisocket.getOutputStream(), true); 
		            
		            
		            System.out.println("Connected to " + clisocket.getInetAddress());
		            sendBtn.setEnabled(true);
		            connectBtn.setEnabled(false);
		            msgListener ml = new msgListener();
	     			ml.start();
          		
          		}

	    		if(evt.getSource() == sendBtn)
	    		{
					
		            	GregorianCalendar calendar = new GregorianCalendar();
		        		Date timeStrap = calendar.getTime();
			            
			            userIn = inMessage.getText();
			            out.println("\n \n" + timeStrap + " | FROM CLIENT> " + userIn );
						connectBtn.setEnabled(false);
						inMessage.setText("");
						    		
	    		}
				

				
          	}
          	
          	catch	(Exception e)
          		 {
          		
          			chatArea.setText( ("Connection Error") );
	    	
          		
          		}
          
    }

	public void keyTyped(KeyEvent e) {}
   	public void keyReleased(KeyEvent e) {}
  	public void keyPressed(KeyEvent e) 
  	{
  		 		
        String userIn ;
        String ipAdress;
     	int key = e.getKeyCode();
   		 	
   		if (key == KeyEvent.VK_ENTER) 
   			{
    			System.out.println("ENTER pressed");
    			GregorianCalendar calendar = new GregorianCalendar();
		        Date timeStrap = calendar.getTime();
			            
			    userIn = inMessage.getText();
			    out.println("\n \n" + timeStrap + " | FROM CLIENT> " + userIn );
			    
				chatArea.append(userIn);
			    chatArea.setText(chatArea.getText());
			    
			    connectBtn.setEnabled(false);
				inMessage.setText("");
						
       		}
     		
    }
          
          
class msgListener extends Thread
{
	
	public void run()
	{
		while(true)
		{
		 		
		 	
		 	
		 	try{
		 	
		 		String fromServer;


				
				//Commented out sound for now, I need to make it conditional so I can only play it once in a while
		        
		        InputStream inSound = new FileInputStream("chat.au");
		        AudioStream as = new AudioStream(inSound); 
	            fromServer = in.readLine();
		       
		       	if (fromServer != null)
		       	{
		       		AudioPlayer.player.start(as);
		       	} 
		       	
		        GregorianCalendar calendar = new GregorianCalendar();
		        Date timeStrap = calendar.getTime();

	            
	            System.out.println( timeStrap + " | From Server> " + fromServer);
				
	            
	            chatArea.setText( chatArea.getText() + "\n" + fromServer );
	            
				
	            	
		
		 	}catch(Exception e){e.printStackTrace();}
	
	}


}
                
}	
	       
	          
  

   
  public static void main ( String[] args )throws IOException
  {
	    ClientGui clientApp  = new ClientGui() ;
	    
	    WindowQuitter wquit = new WindowQuitter(); 
	    clientApp.addWindowListener( wquit );
	    
	    clientApp.setSize( 573, 380);
	    clientApp.setVisible( true );
	            
  }
}
   
	class  WindowQuitter  extends WindowAdapter 
	{
	  public void windowClosing( WindowEvent e )
	  {
	    System.exit( 0 );   
	  }
	}


				//This is for parsing, it would have to go in the server,

		        /*  out.close();
		            in.close();
		            clisocket.close();*/
		            
		            //String  s = "hello";
		    		//String test = s.substring(1,1);
		            //if(test.equalsIgnoreCase("/"))